
pipeline {
    agent any

    options {
        timestamps()                    // 在日志中打印时间
        timeout(time:1, unit:'HOURS')   // 流水线超时设置为1H
        // retry(2)                        // 失败重试2次
    }

    parameters {
        choice(name: 'EnvType', choices: ['dev20', "lufei"], description: '发布的环境')
        string(name: 'SqlFile', defaultValue: '', description: '要发布的Sql文件')
        string(name: 'Databases', defaultValue:'', description: "WebGasErpCallNew2,DccDataBaseA,DccDataBaseB,DccDataBaseC,DccDataBaseD,DccDataBaseE,DccDataBaseH,DccDataBaseI,DccDataBaseJ,DccDataBaseK,DccDataBaseL<br/><h5 style='color:red;'>注意：文件内不要包含 [USE ****]</h5>")
    }

    stages {
        stage("InitParamters") {
            steps {
                script {
                    wrap([$class: 'BuildUser']) {
                        buildName "${BUILD_NUMBER}-${env.BUILD_USER}-${EnvType}"
                    }
                    if (SqlFile == "") {
                        println "The Sql File does not exists."
                        error "This pipeline stops here!"
                    }

                    json_file = "C:\\Jenkins\\resources\\input.lanyang.json"
                    Boolean isExists = fileExists json_file
                    if (!isExists) {
                        println "The Input_Json File does not exists."
                        error "This pipeline stops here!"
                    }
                    prop = readJSON file : json_file
                    publishFolder = prop.projects.publishFolder ? prop.projects.publishFolder : ""
                    println "publishFolder: " + publishFolder
                    sharedFolder = prop.envs[EnvType].sharedFolder ? prop.envs[EnvType].sharedFolder : ""
                    println "sharedFolder: " + sharedFolder
                    packageFolder = prop.envs[EnvType].packageFolder ? prop.envs[EnvType].packageFolder : ""
                    println "packageFolder: " + packageFolder

                    dbHost = prop.envs[EnvType].Database.host ? prop.envs[EnvType].Database.host : ""
                    println "dbHost: " + dbHost
                }
            }
        }

        stage('CopyPackage') {
            agent {  
                node { 
                    label 'label-master'
                }
            } 
            steps {
                withCredentials([usernamePassword(credentialsId: 'lufei.ssh', usernameVariable: 'USERNAME', passwordVariable: 'PASSWORD')]) {
                    timeout(time:30, unit:'MINUTES') {
                        script {
                            println "start copy sql file:" + SqlFile
                            bat """
                                set fileName=${SqlFile}
                                set sharedFolder="${sharedFolder}"
                                set today=%date:~0,4%%date:~5,2%%date:~8,2%
                                set filePath=.\\SqlScript\\%fileName%
                                
                                cd /d "${publishFolder}"

                                :: 主节点时不用copy包, 设置sharedFolder=""
                                IF %sharedFolder% == "" (
                                    echo "[Debug:info] sharedFolder is empty"
                                    GOTO OK
                                )
                                
                                echo "[Debug:info] start connect sharedFolder: %sharedFolder%"
                                net use %sharedFolder% ${PASSWORD} /user:"${USERNAME}"
                                IF %ERRORLEVEL% NEQ 0 GOTO ERROR

                                If exist %sharedFolder%\\%fileName% (
                                    echo "[Debug:info] start delete previous package"
                                    del /q %sharedFolder%\\%fileName%
                                )
                                IF %ERRORLEVEL% NEQ 0 GOTO ERROR

                                echo "[Debug:info] start copy package to deploy package folder: %sharedFolder%"
                                xcopy /c /y /i %filePath% "%sharedFolder%\\"
                                IF %ERRORLEVEL% NEQ 0 GOTO ERROR

                                :OK
                                ECHO command success
                                EXIT 0

                                :ERROR
                                ECHO command failed
                                EXIT 1
                            """                            
                        }
                    }
                }
            }
        }
        
        stage('Deploy') {
            agent { label "label-${EnvType}" }

			steps {
                withCredentials([usernamePassword(credentialsId: "db.${EnvType}", usernameVariable: 'USERNAME', passwordVariable: 'PASSWORD')]) {
                    timeout(time:5, unit:'MINUTES') {
                        script {
                            for (database in Databases.split(';')) {
                                println "start deploy database: "  + database
                                if (sharedFolder == "") {
                                    packageFolder = publishFolder + "\\SqlScript"
                                }
                                println "packageFolder: " + packageFolder
                                
                                bat """
                                    SET dbHost=${dbHost}
                                    SET dbUserID=${USERNAME}
                                    SET dbPassword=${PASSWORD}
                                    set dbName=${database}
                                    set sqlfile="${packageFolder}\\${SqlFile}"

                                    IF NOT EXIST %sqlfile% (
                                        ECHO %sqlfile% does not exist.
                                        GOTO ERROR
                                    )

                                    sqlcmd -S %dbhost% -U %dbUserID% -P %dbPassword% -d %dbName% -i %sqlfile%  
                                    IF %ERRORLEVEL% NEQ 0 GOTO ERROR

                                    :OK
                                    ECHO command success
                                    EXIT 0
                                    
                                    :ERROR
                                    ECHO command failed
                                    EXIT 1
                                """
                            }
                        }
                    }
                }
			}			
        }
    }

    post {
        success {
            wrap([$class: 'BuildUser']) {
                echo '恭喜您，构建成功！！！'
                mail subject: "CI报告: ${env.JOB_NAME} [${env.BUILD_NUMBER}] 执行成功",
                body: """
                    <style>
                    ul li { padding: 8px 0; }
                    ul li .title { min-width: 130px; display: inline-block; }
                    </style>
                    <div id="content">
                        <div id="sum2">
                            <h2><font color=#00CD00>Jenkins 运行成功</font></h2>
                            <ul>
                                <li><label class="title">发布环境:</label> ${params.EnvType}</li>
                                <li><label class="title">发布文件:</label> ${params.SqlFile}</li>
                                <li><label class="title">发布数据库:</label> <font color=#00CD00>${params.Databases}</font></li>
                                <li><label class="title">发布人:</label> ${BUILD_USER}</li>
                            </ul>
                        </div>
                    </div>
                    """,
                charset: 'utf-8',
                from: 'ifelse01@163.com',
                mimeType: 'text/html',
                to: "${env.BUILD_USER_EMAIL}, lufei@lanyang.com"
            }
        }
        failure {
            wrap([$class: 'BuildUser']) {
                echo '抱歉，构建失败！！！'
                mail subject: "CI报告: ${env.JOB_NAME} [${env.BUILD_NUMBER}] 执行失败",
                body: """
                    <style>
                    ul li { padding: 8px 0; }
                    ul li .title { min-width: 130px; display: inline-block; }
                    </style>
                    <div id="content">
                        <div id="sum2">
                            <h2><font color=#EE0000>Jenkins 运行失败</font></h2>
                            <ul>
                                <li><label class="title">发布环境:</label> ${params.EnvType}</li>
                                <li><label class="title">发布文件:</label> ${params.SqlFile}</li>
                                <li><label class="title">发布数据库:</label> <font color=#EE0000>${params.Databases}</font></li>
                                <li><label class="title">发布人:</label> ${BUILD_USER}</li>
                            </ul>
                        </div>
                    </div>
                """,
                charset: 'utf-8',
                from: 'ifelse01@163.com',
                mimeType: 'text/html',
                to: "${env.BUILD_USER_EMAIL}, lufei@lanyang.com"
            }
        }
    }
}
